package handler;

import entity.BaseHead;
import entity.enums.HikMsgType;
import global.Global;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author zhouwz
 * @date 2020/11/24 10:15
 */
public class MsgDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        byteBuf.markReaderIndex();
        if (byteBuf.readableBytes() > Global.HEAD_SIZE) {
            CharSequence charSequence = byteBuf.readCharSequence(4, Charset.defaultCharset());
            // 读取头标记匹配约定信息
            if (Global.HEAD_FLAG.equals(charSequence.toString())) {
                BaseHead baseHead = new BaseHead(byteBuf.readShort(), HikMsgType.getHikMsgType(byteBuf.readShort()));
                byteBuf.resetReaderIndex();
                // 读取类型 回滚读取索引 比较剩余可读字节大于等于全部报文长度
                if (baseHead.getLen() <= byteBuf.readableBytes()) {
                    byte[] msgPojo = new byte[baseHead.getLen()];
                    byteBuf.readBytes(msgPojo);
                    baseHead.setData(msgPojo);
                    list.add(baseHead);
//                    if (byteBuf.readableBytes() > 0) {
//                        byteBuf.clear();
//                    }
                }
            }
        }
    }
}
